# -*- coding: utf-8 -*-
from oauth.models import Ouser
from rest_framework import serializers
from blog.models import Article, Tag, Category, Timeline
from tool.models import ToolLink, ToolCategory



class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ouser
        fields = ('id', 'username', 'first_name', 'link', 'avatar')
        # fields = '__all__'
        # exclude = ('password','email')
class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id','name')

class ArticleSerializer(serializers.ModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')
    category_info = CategorySerializer(read_only=True)
    author_id = serializers.PrimaryKeyRelatedField(queryset=Ouser.objects.all(), write_only=True)
    category_id = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), write_only=True)
    tags_info = TagSerializer(
        many=True,
        read_only=True,
    )
    keywords = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='name'
    )

    class Meta:
        model = Article
        fields = ('id','author','author_id','title','body','category_id','category_info','tags_info','keywords',\
                  'is_public','is_top','img_link','create_date','update_date','views','slug')
        # exclude = ('body','summary')
        extra_kwargs = {
            'body': {
                'write_only': True
            },

        }

    def create(self, validated_data):
        # validated_data-> {'publish': {'pk': '1'}, 'title': 'go', 'price': 100,'pub_date': datetime.date(2012, 12, 12), 'authors': [<Author: alex>, <Author: egon>]}
        category = validated_data.pop('category_id')
        author = validated_data.pop('author_id')
        article = Article.objects.create(title=validated_data["title"],body=validated_data["body"],
                                         category=category,author=author,slug=validated_data["slug"])
        return article

class TimelineSerializer(serializers.ModelSerializer):
    class Meta:
        model = Timeline
        fields = '__all__'


class ToolCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = ToolCategory
        fields = '__all__'


class ToolLinkSerializer(serializers.ModelSerializer):
    category = ToolCategorySerializer()

    class Meta:
        model = ToolLink
        fields = '__all__'
